package com.example.sharesinfo.fragment;


import android.content.Intent;
import android.os.Bundle;

import androidx.fragment.app.Fragment;

import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.example.sharesinfo.R;
import com.example.sharesinfo.base.BaseFragment;
import com.example.sharesinfo.entity.Constants;
import com.example.sharesinfo.manager.DialogManager;
import com.example.sharesinfo.ui.TradingActivity;
import com.example.sharesinfo.utils.LogUtils;
import com.example.sharesinfo.utils.OkHttpUtils;
import com.example.sharesinfo.utils.SpUtils;
import com.example.sharesinfo.view.DialogView;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

/**
 * A simple {@link Fragment} subclass.
 */
public class InformationFragment extends BaseFragment implements View.OnClickListener {
    private InformationFragment fa;
    //页面控件
    private TextView tv_sum_money;
    private TextView tv_sumStock_value;
    private TextView tv_profit_or_loss;
    private TextView tv_valid_money;
    private TextView tv_rank;
    private LinearLayout ll_buy;
    private LinearLayout ll_sell;
    private LinearLayout ll_position;
    private LinearLayout ll_history;
    //Handler返回
    private static final int QUERYDATASUCCESS = 1001;
    private static final int QUERYDATASFAILED = 1002;
    private static final int ActivateAccounSUCCESS = 1003;
    private static final int ActivateAccounFAILED = 1004;
    //开户弹框
    private DialogView mActivateAccountView;
    private boolean isActivate;
    private Handler mHandler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            switch (msg.what) {
                case QUERYDATASUCCESS:
                    isActivate = true;
                    JSONObject result = (JSONObject) msg.obj;
                    try {
                        tv_sum_money.setText(result.getString("SumMoney"));//
                        tv_sumStock_value.setText(result.getString("ValidMoney"));//ValidMoney
                        tv_valid_money.setText(result.getString("SumStockValue"));//SumStockValue
                        //tv_sum_money总资产：19.68w<===可用
                        //tv_sumStock_value可用资产：0.32w<==总市值
                        //tv_valid_money总市值：199998.7
                        tv_profit_or_loss.setText(result.getString("Profit_or_Loss"));
                        tv_rank.setText(result.getString("Rank"));
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                    break;
                case QUERYDATASFAILED:
                    //没有开户默认
                    tv_sum_money.setText("--");
                    tv_sumStock_value.setText("--");
                    tv_profit_or_loss.setText("--");
                    tv_valid_money.setText("--");
                    tv_rank.setText("--");
                    DialogManager.getInstance().show(mActivateAccountView);
                    break;
                case ActivateAccounSUCCESS:
                    DialogManager.getInstance().hide(mActivateAccountView);
                    Toast.makeText(getContext(), msg.obj.toString(), Toast.LENGTH_SHORT).show();
                    queryData();
                    break;
            }
            return false;
        }
    });

    public InformationFragment getFragment() {
        if (fa == null) {
            fa = new InformationFragment();
        }
        return fa;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_information, null);
        initView(view);
        createActivateAccountDialog();
        queryData();
        return view;
    }

    private void queryData() {
        String url = "http://119.23.221.142/api/account/GetStockMainPage?UserId="
                + SpUtils.getInstance().getString(Constants.SP_USER_ID, "");
        LogUtils.i("链接" + url);
        OkHttpUtils.getInstance().Get(url, new OkHttpUtils.okHttpListener() {
            Message message = mHandler.obtainMessage();

            @Override
            public void OnSuccess(String s, int code) throws JSONException {
                JSONObject object = new JSONObject(s);
                if (object.getString("code").equals("200")) {
                    JSONObject object1 = object.getJSONObject("data");
                    message.what = QUERYDATASUCCESS;
                    message.obj = object1;
                    mHandler.sendMessage(message);
                } else {
                    message.what = QUERYDATASFAILED;
                    message.obj = object;
                    mHandler.sendMessage(message);
                }
            }

            @Override
            public void OnFailed(String s) {
                message.what = 404;
                message.obj = s;
                mHandler.sendMessage(message);
            }
        });

    }

    private void initView(View view) {
        isActivate = false;
        tv_sum_money = view.findViewById(R.id.tv_sum_money);
        tv_sumStock_value = view.findViewById(R.id.tv_sumStock_value);
        tv_profit_or_loss = view.findViewById(R.id.tv_profit_or_loss);
        tv_valid_money = view.findViewById(R.id.tv_valid_money);
        tv_rank = view.findViewById(R.id.tv_rank);
        ll_buy = view.findViewById(R.id.ll_buy);
        ll_sell = view.findViewById(R.id.ll_sell);
        ll_position = view.findViewById(R.id.ll_position);
        ll_history = view.findViewById(R.id.ll_history);
        ll_buy.setOnClickListener(this);
        ll_sell.setOnClickListener(this);
        ll_position.setOnClickListener(this);
        ll_history.setOnClickListener(this);
    }

    /**
     * @type
     * @explain 创建开户提示框
     * @author
     * @creat time
     */

    private void createActivateAccountDialog() {
        mActivateAccountView = DialogManager.getInstance().initView(getContext(),
                R.layout.dialog_activate_account);
        //外部点击无效
        mActivateAccountView.setCancelable(false);
        ImageView iv_back = mActivateAccountView.findViewById(R.id.iv_back);
        iv_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                DialogManager.getInstance().hide(mActivateAccountView);
            }
        });
        TextView tv_activate = mActivateAccountView.findViewById(R.id.tv_activate);
        tv_activate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ActivateAccount();
            }
        });

    }

    /**
     * 请求开户
     * POST
     */
    private void ActivateAccount() {
        String urlRoot = "http://119.23.221.142/api/account/ActivateAccount?";
        Map<String, String> datas = new HashMap<String, String>();
        datas.put("UserId", SpUtils.getInstance().getString(Constants.SP_USER_ID,""));
        OkHttpUtils.getInstance().Post(urlRoot, null, datas,
                null, null, new OkHttpUtils.okHttpListener() {
                    Message message = mHandler.obtainMessage();

                    @Override
                    public void OnSuccess(String s, int code) throws JSONException {
                        JSONObject object = new JSONObject(s);
                        message.what = ActivateAccounSUCCESS;
                        message.obj = object.getString("message");
                        mHandler.sendMessage(message);
                    }

                    @Override
                    public void OnFailed(String s) {

                    }
                });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ll_buy:
                if (isActivate) {
                    TradingActivity.startActivity(getContext(), 0);
                } else {
                    DialogManager.getInstance().show(mActivateAccountView);
                }

                break;
            case R.id.ll_sell:
                if (isActivate) {
                    TradingActivity.startActivity(getContext(), 1);
                } else {
                    DialogManager.getInstance().show(mActivateAccountView);
                }
                break;
            case R.id.ll_position:
                if (isActivate) {
                    TradingActivity.startActivity(getContext(), 2);
                } else {
                    DialogManager.getInstance().show(mActivateAccountView);
                }

                break;
            case R.id.ll_history:
                if (isActivate) {
                    TradingActivity.startActivity(getContext(), 3);
                } else {
                    DialogManager.getInstance().show(mActivateAccountView);
                }
                break;
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        queryData();
    }
}
